from django.shortcuts import render
from django.views import View
# Create your views here.
from django.http import JsonResponse
# 导入省市区模型类
from apps.areas.models import Area
# 使用django缓存进行省市区数据获取
from django.core.cache import cache
from django_redis import get_redis_connection
import re
import json
from django.contrib.auth import logout
# 导入地址表进行保存
from apps.users.models import Address
from meiduo_mall.settings.dev import logger

class AddressView(View):
    """
    获取省数据
    """

    def get(self, request):
        # 判断缓存中是否已经存储过数据，如果存储过直接返回缓存数据
        province_list = cache.get('province_list')
        if province_list:
            return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})
        else:
            # 1、查询所有的省的数据
            data = Area.objects.filter(parent_id=None)
            # 2、将省的数据存入列表进行返回
            province_list = []
            for s in data:
                province_list.append({
                    'id': s.id,
                    'name': s.name
                })
            # 3、返回结果
            return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})


class SubAreasView(View):
    """
    获取市的信息
    获取区县的信息
    """

    def get(self, request, pk):
        """

        :param request:
        :param pk: 前端传递的省的id值或者是前端传递的市的id
        :return:
        """
        # 判断缓存中是否已经存储过数据，如果存储过直接返回缓存数据
        sub_data = cache.get('sub_data_%d' % pk)
        if sub_data:
            return JsonResponse({
                'code': 0,
                'errmsg': 'ok',
                'sub_data': sub_data
            })
        else:
            # 1、根据pk查询省的信息或市的信息
            s = Area.objects.get(id=pk)
            # 2、根据pk查询省对应的市的信息或区县信息
            citys = Area.objects.filter(parent__id=pk)
            # 3、构造响应数据进行返回
            subs = []
            for city in citys:
                subs.append({
                    'id': city.id,
                    'name': city.name
                })
            # 写入缓存
            cache.set('sub_data_%d' % pk, sub_data, 3600)
            return JsonResponse({
                'code': 0,
                'errmsg': 'ok',
                'sub_data': {
                    'id': s.id,
                    'name': s.name,
                    'subs':subs
                }
            })

class CreateAddresView(View):
    """
    保存地址
    """
    def post(self,request):
        # 获取前端数据　json数据
        json_data = request.body.decode()
        # 2 转化json数据
        dict_data = json.loads(json_data)
        # 3 提取对应的字段数据
        receiver = dict_data.get('receiver')
        province_id = dict_data.get('province_id')
        city_id = dict_data.get('city_id')
        district_id = dict_data.get('district_id')
        place = dict_data.get('place')
        mobile = dict_data.get('mobile')
        tel = dict_data.get('tel')
        email = dict_data.get('email')
        # 4 验证数据
        # 4-1 验证数据完整性
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '参数不完整'}, status=400)
        # 4-2 验证手机号
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式不正确'}, status=400)
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '参数email有误'})
        # 5　保存数据
        # 在地址页面用户是登录的，可以使用reques.user获取用户信息
        address=Address.objects.create(user=request.user, receiver=receiver, title=receiver, province_id=province_id,
                               city_id=city_id,
                               district_id=district_id,
                               place=place,
                               mobile=mobile,
                               tel=tel,
                               email=email)
        # 增加默认地址判断　如果在保存地址是没有默认地址　那么
        # 就将保存的地址作为默认地址
        default_address = request.user.default_address
        if default_address is None:
            request.user.default_address = address
            # request.user.default_address_id = address.id
            # 更新赋值之后需要save()
            request.user.save()

        # 6　返回结果
        return JsonResponse({'code': 0, 'messsage': "ok"})


class UserAddresView(View):
    """
    获取地址
    """
    def get(self,request):
        # 1 获取用户
        user = request.user
        # 2 根据用户查询对应地址信息
        addresses = Address.objects.filter(user = user,is_deleted=False)
        addresses_list = []
        for addres in addresses:
            addresses_list.append({
                "id": addres.id,
                "title": addres.title,
                "receiver": addres.receiver,
                "province": addres.province.name,
                "city": addres.city.name,
                "district": addres.district.name,
                "place": addres.place,
                "mobile": addres.mobile,
                "tel": addres.tel,
                "email": addres.email
            })
        # 3 获取用户的默认地址
        default_address_id = user.default_address.id

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'default_address_id':default_address_id,'addresses': addresses_list})

class UserDefaultAddresView(View):

    def put(self, request, pk):
        # 1、获取用户
        user = request.user
        # 2、获取用户地址
        address = Address.objects.get(user=user, id=pk)
        # 3、设置默认地址
        user.default_address = address
        user.save()
        # 4、返回结果
        return JsonResponse({'code': 0, 'errmsg': 'ok'})


class ChangePasswordView(View):
    """
    修改密码
    """

    def put(self, request):
        # 1、获取数据 ，json形式
        json_data = request.body.decode()
        dict_data = json.loads(json_data)
        old_password = dict_data.get('old_password')
        new_password = dict_data.get('new_password')
        new_password2 = dict_data.get('new_password2')
        # 2、获取用户
        user = request.user
        # 3、校验数据# 验证完整性
        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400, 'errmsg': '数据不完整'}, status=400)
        # 密码校验，原始密码是否正确 check_password方法成功返回true
        if not user.check_password(old_password):
            return JsonResponse({'code': 400, 'errmsg': '密码不正确'}, status=400)
        # 判断密码格式
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', new_password):
            return JsonResponse({'code': 400, 'errmsg': '密码格式不正确'}, status=400)
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', new_password2):
            return JsonResponse({'code': 400, 'errmsg': '密码格式不正确'}, status=400)
        # 判断两次是否一致
        if new_password != new_password2:
            return JsonResponse({'code': 400, 'errmsg': '密码不一致'}, status=400)
        # 4、修改密码 set_password
        user.set_password(new_password)
        user.save()
        # 退出状态保持，将原有的用户删除,实现就是退出登录操作
        logout(request)
        resposne = JsonResponse({'code': 0, 'errmsg': 'ok'})
        resposne.delete_cookie('username')

        # 5、返回结果
        return resposne


class UpdateDestroyAddressView(View):
    """修改和删除地址"""
    # 修改地址
    def put(self,request,pk):

        # 获取json数据
        json_data = request.body.decode()
        dict_data = json.loads(json_data)
        receiver = dict_data.get('receiver')
        province_id = dict_data.get('province_id')
        city_id = dict_data.get('city_id')
        district_id = dict_data.get('district_id')
        place = dict_data.get('place')
        mobile = dict_data.get('mobile')
        tel = dict_data.get('tel')
        email = dict_data.get('email')

        # 2、验证数据
        # 2-1、验证数据的完整性
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '参数不完整'}, status=400)
        # 2-2、验证手机号
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式不正确'}, status=400)
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '参数email有误'})
        # 3、获取要修改的地址对象  这里老师写的推荐使用
        # address = Address.objects.get(id=pk)
        # # 赋值修改,必须进行save保存
        # address.receiver =receiver
        # address.save()
        # update方法进行修改不需要save res返回的结果是更新状态{'name':'python'}  name=python
        # del dict_data['province']
        # del dict_data['city']
        # del dict_data['district']
        # res = Address.objects.filter(id=pk).update(**dict_data)
        # # 再次查询更新后的数据
        # address=Address.objects.get(id=pk)
        #
        #
        # 返回结果
        # return JsonResponse({})


        # 更新数据 这里自己写的
        Address.objects.filter(id=pk).update(
            user=request.user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )
        # 构成响应数据
        address  = Address.objects.get(id=pk)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code':0,'errmsg':'ok','address':address_dict})

    def delete(self, request,pk):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=pk)

        except :
            return JsonResponse({'code':400,'errmsg':'获取数据失败'},status=400)
        # 将地址逻辑删除设置为True
        address.is_deleted = True
        address.save()
        # 响应删除地址结果
        return JsonResponse({'code': 0,'errmsg': '删除地址成功'})

class UpdateTitleAddressView(View):
    # 修改地址标题
    def put(self, request, pk):
        """

        :param request:
        :param pk: 地址id
        :return:
        """
        # 获取标题 json
        json_data = request.body.decode()
        dict_data = json.loads(json_data)
        title = dict_data.get('title')
        try:
            # 查询地址
            address = Address.objects.get(id=pk)
        except:
            return JsonResponse({'code': 400, 'errmsg': '设置地址标题失败'})
        # 更新标题
        address.title = title
        address.save()
        # 4.响应删除地址结果
        return JsonResponse({'code': 0, 'errmsg': '设置地址标题成功'})

